<template>
  <page-container title="注册" :showBack="true">
    <template v-slot:nav-left>
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
      </view>
    </template>
    <view class="register-container">
      <!-- 注册表单 -->
      <view class="register-form">
        <!-- 姓名输入 -->
        <view class="form-item">
          <input class="form-input" v-model="formData.name" placeholder="请输入姓名" type="text" maxlength="30"
            @input="onNameInput" />
        </view>

        <!-- 手机号输入 -->
        <view class="form-item">
          <input class="form-input" v-model="formData.phone" placeholder="请输入手机号" type="number" maxlength="11" :disabled="isSkipPhoneValid"
            @input="onPhoneInput" />
        </view>

        <!-- 验证码输入 -->
        <view class="form-item verification-item" v-if="!isSkipPhoneValid">
          <input class="form-input verification-input" v-model="formData.verificationCode" placeholder="请输入您的验证码"
            type="number" maxlength="6" @input="onVerificationInput" />
          <button class="verification-btn" :class="{ disabled: !canSendCode }" @click="sendVerificationCode">
            <text class="verification-text">{{ verificationText || '获取验证码' }}</text>
          </button>
        </view>

        <!-- 密码输入 -->
        <view class="form-item password-item">
          <input class="form-input password-input" v-model="formData.password" placeholder="请输入密码"
            :password="!showPassword" @input="onPasswordInput" />
          <view class="password-toggle" @click="togglePassword">
            <uni-icons class="eye-icon" :type="showPassword ? 'eye' : 'eye-slash'" size="20"
              color="#999999"></uni-icons>
          </view>
        </view>

        <!-- 确认密码输入 -->
        <view class="form-item password-item">
          <input class="form-input password-input" v-model="formData.confirmPassword" placeholder="请再次输入密码"
            :password="!showConfirmPassword" @input="onConfirmPasswordInput" />
          <view class="password-toggle" @click="toggleConfirmPassword">
            <uni-icons class="eye-icon" :type="showConfirmPassword ? 'eye' : 'eye-slash'" size="20"
              color="#999999"></uni-icons>
          </view>
        </view>
        <!-- 身份证号 -->
        <view class="form-item">
          <input class="form-input" v-model="formData.idCardNo" placeholder="请输入身份证号" @input="onIdCardNoInput" />
        </view>

        <!-- 身份证照片上传 -->
        <view class="upload-section">
          <view class="upload-title">
            <text class="title-text">身份证照片 (上传图片大小不能超过5M)</text>
          </view>
          <view class="upload-container">
            <view class="upload-item" @click="uploadIdCard('front')">
              <view class="upload-area" v-if="!formData.idCardFront">
                <text class="upload-icon">+</text>
                <text class="upload-text">身份证正面</text>
              </view>
              <image v-else :src="formData.idCardFront || ''" mode="aspectFill" class="uploaded-image" />
            </view>
            <view class="upload-item" @click="uploadIdCard('back')">
              <view class="upload-area" v-if="!formData.idCardBack">
                <text class="upload-icon">+</text>
                <text class="upload-text">身份证反面</text>
              </view>
              <image v-else :src="formData.idCardBack || ''" mode="aspectFill" class="uploaded-image" />
            </view>
          </view>
        </view>

        <!-- 注册按钮 -->
        <view class="register-button">
          <!-- :class="{ disabled: !canRegister }" -->
          <button class="register-btn" @click="register">
            <text class="register-text">注册</text>
          </button>
        </view>

        <!-- 协议同意 -->
        <view class="agreement-section">
          <view class="agreement-item" @click="toggleAgreement">
            <view class="checkbox" :class="{ checked: isAgreed }">
              <!-- 优先使用 uni-icons -->
              <text class="checkbox-text" v-if="isAgreed">
                <uni-icons type="checkmark" size="16" color="#fff"></uni-icons>
              </text>
              <!-- 如果 uni-icons 不显示，CSS 会显示备用勾选图标 -->
            </view>
            <text class="agreement-text">
              我已知晓
              <text class="link-text" @click.stop="openPrivacyPolicy">《隐私政策》</text>
              和
              <text class="link-text" @click.stop="openServiceAgreement">《注册和服务协议》</text>
            </text>
          </view>
        </view>
      </view>
    </view>
  </page-container>
</template>

<script>
import config from '@/config'
import { uploadToOss } from '@/utils/ossUpload'
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

export default {
  name: 'RegisterPage',
  components: {
    uniIcons
  },

  data() {
    return {
      formData: {
        name: '',
        phone: '',
        verificationCode: '',
        password: '',
        confirmPassword: '',
        idCardFront: '',
        idCardBack: '',
        idCardNo: ''
      },
      showPassword: false,
      showConfirmPassword: false,
      isAgreed: false,
      countdown: 0,
      timer: null,
      frontPath: '',
      backPath: '',
	  isSkipPhoneValid:false,
    }
  },
  onLoad(options) {
	  if(options.phone){
		  this.formData.phone=options.phone;
		  this.isSkipPhoneValid=true;
	  }
  },
  computed: {
    // 是否可以发送验证码
    canSendCode() {
      return this.formData.phone && this.formData.phone.length === 11
      //&& this.countdown === 0
    },
    // 验证码按钮文本
    verificationText() {
      if (this.countdown > 0) {
        return `${this.countdown}s`
      }
      return '获取验证码'
    },
    // 是否可以注册
    canRegister() {
      return this.formData.name &&
        this.formData.phone && this.formData.phone.length === 11 &&
        this.formData.verificationCode && this.formData.verificationCode.length === 6 &&
        this.formData.password &&
        this.formData.confirmPassword &&
        this.formData.password === this.formData.confirmPassword &&
        this.formData.idCardFront &&
        this.formData.idCardBack &&
        this.formData.idCardNo &&
        this.isAgreed
    }
  },
  methods: {
    goBack() {
      setTimeout(() => {
        uni.navigateBack()
      }, 100)
    },
    // 身份证号输入处理
    onIdCardNoInput(e) {
      if (e && e.detail && e.detail.value !== undefined) {
        this.formData.idCardNo = e.detail.value
      }
    },
    // 姓名输入处理
    onNameInput(e) {
      if (e && e.detail && e.detail.value !== undefined) {
        this.formData.name = e.detail.value
      }
    },
    // 手机号输入处理
    onPhoneInput(e) {
      if (e && e.detail && e.detail.value !== undefined) {
        this.formData.phone = e.detail.value
      }
    },
    // 验证码输入处理
    onVerificationInput(e) {
      if (e && e.detail && e.detail.value !== undefined) {
        this.formData.verificationCode = e.detail.value
      }
    },
    // 密码输入处理
    onPasswordInput(e) {
      if (e && e.detail && e.detail.value !== undefined) {
        this.formData.password = e.detail.value
      }
    },
    // 确认密码输入处理
    onConfirmPasswordInput(e) {
      if (e && e.detail && e.detail.value !== undefined) {
        this.formData.confirmPassword = e.detail.value
      }
    },
    // 切换密码显示
    togglePassword() {
      this.showPassword = !this.showPassword
    },
    // 切换确认密码显示
    toggleConfirmPassword() {
      this.showConfirmPassword = !this.showConfirmPassword
    },
    // 发送验证码
    sendVerificationCode() {
      if (!this.canSendCode) {
        return
      }
      if (this.countdown > 0) {
        uni.showToast({
          title: `${this.countdown}s后可重新发送`,
          icon: 'none'
        })
        return
      }

      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }

      let params = {
        cusPhone: this.formData.phone,
        scene: 'REGISTER'
      }
      this.$http.post('/applet/customer/sendSms', params).then(res => {
        uni.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
		// 开始倒计时
		this.countdown = 60
		this.timer = setInterval(() => {
		  this.countdown--
		  if (this.countdown <= 0) {
		    clearInterval(this.timer)
		    this.timer = null
		  }
		}, 1000)
      })
    },
    // 检查 OSS Client 状态
    checkOSSClient() {
      const app = getApp()
      const client = app.getOSSClient()

      if (!client) {
        uni.showToast({
          title: 'OSS客户端未初始化，请稍后重试',
          icon: 'none'
        })
        return false
      }

      return true
    },

    // 上传身份证
    uploadIdCard(type) {
      // 先检查 OSS Client 是否可用
      if (!this.checkOSSClient()) {
        return
      }

      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const filePath = res.tempFilePaths[0]
          // 检查文件大小（5MB = 5 * 1024 * 1024 bytes）
          uni.getFileInfo({
            filePath: filePath,
            success: async (fileInfo) => {
              const maxSize = 5 * 1024 * 1024 // 5MB
              if (fileInfo.size > maxSize) {
                uni.showToast({
                  title: '图片大小不能超过5M',
                  icon: 'none'
                })
                return
              }
              // 显示上传进度
              uni.showLoading({
                title: '上传中...'
              })
              let fileSuffix = `${res.tempFiles[0].path.split('.').pop()}`
              let OssParams = {
                filePath,
                dir: config.ossConfig.ossDevDepositAddress, // 可选，不传读 config.ossConfig.ossDevDepositAddress
                ext: fileSuffix           // 可选
              }
              // #ifdef H5
              OssParams.filePath = res.tempFiles[0]
              // #endif
              const { key, url } = await uploadToOss(OssParams)
              uni.hideLoading()
              // 保存图片路径
              if (type === 'front') {
                this.formData.idCardFront = url
                this.frontPath = key
              } else {
                this.formData.idCardBack = url
                this.backPath = key
              }
              uni.showToast({
                title: '上传成功',
                icon: 'success'
              })
              return

              // 获取全局 OSS Client
              const app = getApp()
              const client = app.getOSSClient()
              console.log('上传使用的 OSS Client:', client)

              // 显示上传进度
              uni.showLoading({
                title: '上传中...'
              })

              client.multipartUpload(`${config.ossConfig.ossDevDepositAddress}${new Date().getTime()}${fileSuffix}`, res.tempFiles[0]).then(res => {
                console.log(res, 'oss上传成功');//此处就已经上传成功了
                uni.hideLoading()

                // 保存图片路径
                if (type === 'front') {
                  this.formData.idCardFront = filePath
                  this.frontPath = res.name
                } else {
                  this.formData.idCardBack = filePath
                  this.backPath = res.name
                }
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
              }).catch(error => {
                uni.hideLoading()
                console.error('OSS上传失败:', error)
                uni.showToast({
                  title: '上传失败，请重试',
                  icon: 'none'
                })
              })
            }
          })
        },
        fail: () => {
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          })
        }
      })
    },
    // 切换协议同意
    toggleAgreement() {
      this.isAgreed = !this.isAgreed
    },
    // 隐私政策
    openPrivacyPolicy() {
      uni.navigateTo({
        url: '/pages/login/privacyPolicy'
      })
    },
    // 服务协议
    openServiceAgreement() {
      uni.navigateTo({
        url: '/pages/login/agreement'
      })
    },
    // 注册
    register() {
      
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        })
        return
      }
      if (this.formData.name.length > 30) {
        uni.showToast({
          title: '姓名最长30位',
          icon: 'none'
        })
        return
      }
      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        })
        return
      }

      if (this.formData.phone.length !== 11) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      // 验证验证码
	  if(!this.isSkipPhoneValid ){
		  if (!this.formData.verificationCode) {
		    uni.showToast({
		      title: '请输入验证码',
		      icon: 'none'
		    })
		    return
		  }
		  
		  if (this.formData.verificationCode.length !== 6) {
		    uni.showToast({
		      title: '请输入正确的6位验证码',
		      icon: 'none'
		    })
		    return
		  }
	  }

      // 密码最小位数：6 位，最大位数16位
      if (this.formData.password.length < 6 || this.formData.password.length > 16) {
        uni.showToast({
          title: '密码长度不能少于6位，不能大于16位',
          icon: 'none'
        })
        return
      }
      // 密码不能包含空格
      if (this.formData.password.includes(' ')) {
        uni.showToast({
          title: '密码不能包含空格',
          icon: 'none'
        })
        return
      }
      // 密码 数字或字母
      if (!/^[a-zA-Z0-9]+$/.test(this.formData.password)) {
        uni.showToast({
          title: '密码只能包含数字或字母',
          icon: 'none'
        })
        return
      }
      // 验证密码一致性
      if (this.formData.password !== this.formData.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return
      }

      // 检查是否已上传身份证
      if (!this.frontPath || !this.backPath) {
        uni.showToast({
          title: '请上传身份证照片',
          icon: 'none'
        })
        return
      }
      // 验证身份证号格式（简单验证）
      const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!idCardRegex.test(this.formData.idCardNo)) {
        uni.showToast({
          title: '请输入正确的身份证号',
          icon: 'none'
        })
        return
      }
      if (!this.isAgreed) {
        uni.showToast({
          title: '请同意隐私政策、注册和服务协议',
          icon: 'none'
        })
        return
      }

      const params = {
        cusName: this.formData.name,
        cusPhone: this.formData.phone,
        password: this.formData.password,
        validCode: this.isSkipPhoneValid?this.isSkipPhoneValid:this.formData.verificationCode,
        frontPath: this.frontPath,
        backPath: this.backPath,
        idCardNo: this.formData.idCardNo
      }

      // console.log('注册参数:', params)

      this.$http.post('/applet/customer/register', params).then(res => {
        uni.showToast({
          title: '您的注册申请已提交，请耐心等待审核',
          icon: 'none'
        })
        // 延迟返回我的页面
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/mine/index'
          })
        }, 800)
      }).catch(error => {
        console.error('注册失败:', error)
        uni.showToast({
          title: error.msg,
          icon: 'none'
        })

      })
    }
  },
  onUnload() {
    // 页面卸载时清除定时器
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/uni.scss';

.register-container {
  min-height: 100vh;
  background-color: #f5f5f6;
  padding-bottom: 40rpx;
}

/* 注册表单 */
.register-form {
  padding: 30rpx;
}

.form-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
}

.form-input {
  flex: 1;
  height: 88rpx;
  font-size: 28rpx;
  color: #333333;
  border: none;
  background: transparent;
}

.form-input::placeholder {
  color: #999999;
}

/* 去除输入框聚焦时的默认边框/高亮 */
.form-input:focus {
  outline: none;
  box-shadow: none;
  border-color: transparent;
  -webkit-appearance: none;
  appearance: none;
}

/* H5 点击高亮取消 */
input {
  -webkit-tap-highlight-color: transparent;
}

/* 验证码输入 */
.verification-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.verification-input {
  flex: 1;
}

.verification-btn {
  width: 200rpx;
  height: 60rpx;
  background-color: #393837;
  border-radius: 8rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.verification-btn.disabled {
  background-color: #cccccc;
}

.verification-text {
  font-size: 24rpx;
  color: $uni-text-color-orange;
}

.verification-btn.disabled .verification-text {
  color: #999999;
}

/* 密码输入 */
.password-item {
  position: relative;
}

.password-input {
  padding-right: 80rpx;
}

.password-toggle {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.eye-icon {
  font-size: 32rpx;
  color: #666666;
}

/* 上传区域 */
.upload-section {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.upload-title {
  margin-bottom: 20rpx;
}

.upload-title .title-text {
  font-size: 28rpx;
  color: #0B1F20;
}

.upload-container {
  display: flex;
  gap: 20rpx;
}

.upload-item {
  flex: 1;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.upload-area {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: 2rpx dashed #d4af37;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #F5F5F6;
}

.upload-icon {
  font-size: 60rpx;
  color: #d4af37;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #666666;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

/* 注册按钮 */
.register-button {
  margin: 40rpx 0;
}

.register-btn {
  width: 100%;
  height: 88rpx;
  background-color: #cccccc;
  border-radius: 12rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.register-btn:not(.disabled) {
  background: linear-gradient(135deg, #d4af37 0%, #f4d03f 100%);
}

.register-text {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: bold;
}

.register-btn.disabled .register-text {
  color: #999999;
}

/* 测试按钮 */
.test-button {
  margin: 20rpx 0;
}

.test-btn {
  width: 100%;
  height: 60rpx;
  background-color: #f0f0f0;
  border-radius: 8rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.test-text {
  font-size: 24rpx;
  color: #666666;
}

/* 协议同意 */
.agreement-section {
  padding: 0 30rpx;
}

.agreement-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #d4af37;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: transparent;
  transition: all 0.3s ease;
  flex-shrink: 0;
  margin-top: 4rpx;
}

.checkbox.checked {
  background-color: #d4af37;
}

.checkbox-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: bold;
}

/* 备用勾选图标样式 */
.checkbox.checked::after {
  content: '';
  width: 18rpx;
  height: 10rpx;
  border: 2rpx solid #ffffff;
  border-top: none;
  border-right: none;
  transform: rotate(-45deg);
  margin-top: -6rpx;
}

.agreement-text {
  font-size: 24rpx;
  color: #666666;
  line-height: 1.5;
  flex: 1;
}

.link-text {
  color: #d4af37;
  text-decoration: underline;
}
</style>
